<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>多图片上传</title>
    <link rel="stylesheet" type="text/css" href="./css/index.css">

</head>

<body>

<div class="container">
    <input type="hidden" id="page" value="{$page}">
    <!--    照片添加    -->
    <div class="z_photo">
        <p>请选择要添加的文件，并上传到布包中</p>
        <div class="z_file">
            <span>选择文件</span>
            <form id="myForm" enctype="multipart/form-data">
                <input type="file" name="avatar" id="file" value="" multiple onchange="imgChange('photo_box','z_file');" />
            </form>
        </div>
    </div>

    <div class="photo_box">

    </div>

    <!--遮罩层-->
    <div class="z_mask">
        <!--弹出框-->
        <div class="z_alert">
            <p>确定要删除文件吗？</p>
            <p>
                <span class="z_cancel">取消</span>
                <span class="z_sure">确定</span>
            </p>
        </div>
    </div>
</div>
<!--<script src="./js/zepto.js"></script>-->
<!--<script src="./js/upload.js"></script>-->
<script src="https://cdn.bootcss.com/jquery/1.9.0/jquery.min.js"></script>
<script src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
<script type="text/javascript">
    //px转换为rem
    (function(doc, win) {
        var docEl = doc.documentElement,
            resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
            recalc = function() {
                var clientWidth = docEl.clientWidth;
                if (!clientWidth) return;
                if (clientWidth >= 640) {
                    docEl.style.fontSize = '100px';
                } else {
                    docEl.style.fontSize = 100 * (clientWidth / 640) + 'px';
                }
            };

        if (!doc.addEventListener) return;
        win.addEventListener(resizeEvt, recalc, false);
        doc.addEventListener('DOMContentLoaded', recalc, false);
    })(document, window);

    function imgChange(obj1, obj2) {
        var page = $('#id').val();
        // var page = $.query.get("page");
        // var token = $.query.get("token");
        // var page = getQueryString('page');
        // var token = getQueryString('token');
        console.log('page', page);
        //console.log('token', token);
        // var arg = argsIndex[1];
        //获取点击的文本框
        var file = document.getElementById("file");
        //存放图片的父级元素
        var imgContainer = document.getElementsByClassName(obj1)[0];
        //获取的图片文件
        var fileList = file.files;
        console.log(fileList);
//             'https://xiaochengxu.rongyip.com/index/Upload/index'
//            $.ajaxSettings.beforeSend = function(xhr,request){
//                console.log(request.header)
////                request.header = {'token':'D7N2jNH2K8VOoVkdTYk9jrIm3wrKfLsTSgWb4DeOL9Ca4WoXUI7e9QAcn2XDNqwG'}
//        }

//            for (var key in fileList) {
//                if( fileList.hasOwnProperty(key) ) {
//                    formData.append( 'avatar' , fileList[key] );
//                }
//            }
        // request.headers.append({token:'D7N2jNH2K8VOoVkdTYk9jrIm3wrKfLsTSgWb4DeOL9Ca4WoXUI7e9QAcn2XDNqwG'})
        // 在这里加上你的 token
//            var formData = new FormData($('file'));
//            console.log(formData);
        var formData =   new FormData($('#myForm')[0]);

//            console.log(fileList[0]);
//            formData.append("avatar",$('#file')[0]);
//            formData.append('avatar',fileList[0])
//            $('#myForm')
//            console.log(formData['avatar']);
        $.ajax({
            type: 'POST',
//              processData:false,
            processData: false,
            contentType: false,
            url: '/index/Upload/index',
            // data to be added to query string:
            // type of data we are expecting in return:
            dataType: 'json',
            data:formData,
            // headers: {
            //   'Content-Type': "multipart/form-data",
            //   "token": token,
            // },
//              context: {avatar:fileList},
            success: function(data){
                // Supposing this JSON payload was received:
                //   {"project": {"id": 42, "html": "<div>..." }}
                // append the HTML to context object.
                // TODO 这个page是跟随url而来要跳转的界面的参数,url是上传成功的图片地址，img是上传成功以后的缩略图
                wx.miniProgram.reLaunch({url: page+'?url='+data.url});
                // wx.miniProgram.reLaunch({url: `${page}?url=${data.url}&img=${data.img}`})
            },
            error: function(xhr, type){
            }
        });
        //文本框的父级元素
        var input = document.getElementsByClassName(obj2)[0];
        var imgArr = [];
        //遍历获取到得图片文件
        for (var i = 0; i < fileList.length; i++) {
            var imgUrl = window.URL.createObjectURL(file.files[i]);
            imgArr.push(imgUrl);
            var img = document.createElement("img");
            if((file.files[i].type).indexOf("image/")==-1) {
                img.setAttribute("src", './file.jpg');
            } else {
                img.setAttribute("src", imgArr[i]);
            }

            var del = document.createElement("div");
            del.setAttribute('class', 'delete_img');
            del.innerHTML = '×';
            var imgAdd = document.createElement("div");
            imgAdd.setAttribute("class", "z_addImg");
            imgAdd.appendChild(img);
            imgAdd.appendChild(del);
            imgContainer.appendChild(imgAdd);
        };
        imgRemove();
    };

    function imgRemove() {
        var imgList = document.getElementsByClassName("delete_img");
        var mask = document.getElementsByClassName("z_mask")[0];
        var cancel = document.getElementsByClassName("z_cancel")[0];
        var sure = document.getElementsByClassName("z_sure")[0];
        for (var j = 0; j < imgList.length; j++) {
            imgList[j].index = j;
            imgList[j].onclick = function() {
                var t = this;
                mask.style.display = "block";
                cancel.onclick = function() {
                    mask.style.display = "none";
                };
                sure.onclick = function() {
                    mask.style.display = "none";
                    t.parentNode.style.display = "none";
                };

            }
        };
    };

    function getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

</script>
</body>

</html>
